/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jmex.model.ogredotscene.loader;

import com.jme.util.resource.ResourceLocatorTool;
import java.io.File;
import java.io.IOException;


import com.jmex.model.ogredotscene.MaterialFilenameFilter;
import com.jmex.model.ogredotscene.gen.Externals;
import com.jmex.model.ogredotscene.gen.Item;
import com.jmex.model.ogredotscene.gen.ResourceGroup;
import com.jmex.model.ogredotscene.gen.ResourceLocation;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author PaulSyntax
 */
public class TextureLoader {

    private Map<String, Material> materials = new HashMap<String, Material>();
    private MaterialLoader materialLoader = new MaterialLoader();

    public void loadbyResourceGroup(ResourceGroup resourceGroup, File baseDir) throws MalformedURLException, IOException {
        for (ResourceLocation resourceLocation : resourceGroup.getResourceLocation()) {
            if (resourceLocation.getType().equals("FileSystem")) {
                String resourceDirName = "";
                resourceDirName = baseDir.getCanonicalPath() + File.separator + resourceLocation.getName() + File.separator;
                File resourceDir = new File(resourceDirName);
                File[] materialFiles = resourceDir.listFiles(new MaterialFilenameFilter());
                for (File file : materialFiles) {
                    materialLoader.load((file.toURI()).toURL());
                    if (materialLoader.getMaterials() != null && materialLoader.getMaterials().size() > 0) {
                        materials.putAll(materialLoader.getMaterials());
                    }
                }

            }

        }
    }

    public void loadbyExternals(Externals externals) {
        List<Item> itemList = externals.getItem();
        for (Item item : itemList) {
            if (item.getType().equals("material")) {
                URL url = ResourceLocatorTool.locateResource(
                        ResourceLocatorTool.TYPE_TEXTURE, item.getFile().getName());
                try {
                    materialLoader.load(url);
                } catch (Exception ex) {
                    Logger.getLogger(TextureLoader.class.getName()).log(Level.SEVERE, null, ex);
                }
                if (materialLoader.getMaterials() != null && materialLoader.getMaterials().size() > 0) {
                    materials.putAll(materialLoader.getMaterials());
                }
            }
        }
    }

    public Map<String, Material> getMaterials() {
        return materials;
    }

    public void setMaterials(Map<String, Material> materials) {
        this.materials = materials;
    }
}
